#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@IDE     ：PyCharm 
@Author  ：kiway
@Date    ：2024/5/29 23:31 
"""
import multiprocessing
import queue
import time
from multiprocessing import Queue as Queue
import numpy as np
from copy import deepcopy
from .. import logger
from .BaseEngine import BaseEngine, CrossBarEvent, EVENT_POLYBAR


class ParrallEngine(BaseEngine):
    """
    该类默认同步收集所有标的的数据，在一定时间内等待所有数据进行返回，超时后，会对超时未返回的标的数据用0.填充

    """

    def __init__(self, symbol_ls, main_engine, sync_strategy):
        super().__init__("截面数据对齐引擎", main_engine)
        self.updated_dict = {}
        self.symbol_ls = symbol_ls
        self.sync_strategy = sync_strategy

    def optimized_sync_bars(self):
        """优化之后的版本
        每当有bars事件后， 更新主表，并判断主表是否已经集齐所有数据
        # TODO 以ndarray的形式来保存截面数据； 主要固定好每个symbol的行
        """
        flag = np.zeros(shape=(len(self.symbol_ls),)).astype(np.bool_)

        cross_data = {"future": [], "spot": []}

        count = 0
        while True:
            event = self._msg_q.get()

            if event.type == EVENT_POLYBAR:
                flag[count] = True

                if event.is_future:

                    cross_data["future"].append(event.data)
                else:
                    cross_data["spot"].append(event.data)

                if np.all(flag):
                    try:
                        self.sync_strategy.on_all_bar(deepcopy(cross_data["spot"]),
                                                      deepcopy(cross_data["future"]))

                    except Exception as e:

                        logger.pretty_print(e)

                    finally:
                        for k, v in cross_data.items():
                            v.clear()

                        flag[:] = False
                        count = 0
                        continue

                count += 1

    def _start(self):
        p = multiprocessing.Process(target=self.optimized_sync_bars)
        p.start()
